package com.zy.chat.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zy.chat.annotation.LoginLogging;
import com.zy.chat.dto.LoginFormDTO;
import com.zy.chat.entity.UserLogin;
import com.zy.chat.mapper.LoginMapper;
import com.zy.chat.service.LoginService;
import com.zy.chat.util.RegexUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import static com.zy.chat.util.RedisContants.*;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;


@Service
public class UserLoginServiceImpl extends ServiceImpl<LoginMapper, UserLogin> implements LoginService {

    @Autowired
    private RedisTemplate redisTemplate;

    @LoginLogging
    @Override
    public   Map<String, Object> login(LoginFormDTO loginFormDTO) {
        String phone=loginFormDTO.getPhoneNumber();
        String cacheCode =(String) redisTemplate.opsForValue().get(LOGIN_CODE_KEY + phone);
        UserLogin userLogin=null;
        if(phone!=null&&phone!=""){
            String code = loginFormDTO.getCode();
            if(cacheCode==null ||!cacheCode.equals(code)) return Collections.emptyMap();
            userLogin = query().eq("phone", phone).one();
        }else{
             userLogin = query().eq("username", loginFormDTO.getUsername()).eq("password", loginFormDTO.getPassword()).one();
        }
        if(userLogin!=null){
            String token= UUID.randomUUID().toString(true);
            Map<String, Object> result = new HashMap<>();
            result.put("user", userLogin);
            result.put("token", token);
            LoginFormDTO userDTO = BeanUtil.copyProperties(userLogin, LoginFormDTO.class);
            Map<String, Object> userMap = BeanUtil.beanToMap(userDTO);
            String key=LOGIN_USER_KEY+token;
            redisTemplate.opsForHash().putAll(key,userMap);
            redisTemplate.expire(key,LOGIN_USER_TTL,TimeUnit.HOURS);
            return result;
        }else{
            return Collections.emptyMap();
        }
    }

    @Override
    public Boolean getCode(String phone) {
        if (RegexUtils.isPhoneInvalid(phone)) {
            return false;
        }
        String code = RandomUtil.randomNumbers(6);
        System.out.println(code);
        log.debug(code);
        redisTemplate.opsForValue().set(LOGIN_CODE_KEY+phone,code,LOGIN_CODE_TTL, TimeUnit.MINUTES);
        return  true;
    }
}
